# coding=utf8
__author__ = 'Soul'
from DbConnection import *

import MySQLdb
from MySQLdb import Error
from core.Logger import *

class MysqlDbConnection(DbConnection):
    def __init__(self, host, port, user, password, dbname):
        self.__type__ = 'mysql'
        self.__host__ = host
        self.__port__ = port
        self.__user__ = user
        self.__password__ = password
        self.__dbname__ = dbname
        self.__conn__ = None
        self.__cursor__ = None

        # for mysql, we connect db at very beginning
        self.__connect()

    def type(self):
        return self.__type__

    def close(self):
        if not self.__conn__ == None:
            self.__conn__.close()
        if not self.__cursor__ == None:
            self.__cursor__.close()

    def __connect(self):
        if self.__conn__ == None:
            self.__conn__ = MySQLdb.connect(
                db = self.__dbname__,
                host= self.__host__,
                user= self.__user__,
                passwd= self.__password__,
                port= (int)(self.__port__),
                charset = "utf8")

            #self.__conn__.select_db(self.__dbname__)
        return self.__conn__

    def __cursor(self):
        if self.__cursor__ == None:
            if not self.__conn__ == None:
                return self.__conn__.cursor()
        return self.__cursor__

    def do_insert(self, sql, params):
        global logger
        logger.info('[MYSQL]: Insert following sql:')
        logger.info(sql)
        logger.info(params)
        import threading
        mutex = threading.Lock()
        rtrn_val = 1
        if mutex.acquire(1):
            conn = self.__connect()
            cu   = self.__cursor()
            try:
                if params == None:
                    rtrn_val = cu.execute(sql)
                else:
                    rtrn_val = cu.execute(sql, params)
            except MySQLdb.Error, e:
                print str(e)
                logger.error('[MYSQL]: insert value failed:' + e.args[0])
                rtrn_val = 0
            finally:
                conn.commit()
                mutex.release()

    def do_insert_many(self, sql, params):
        global logger
        logger.info('[MYSQL]: Insert many following sql:')
        logger.info(sql)
        import threading
        mutex = threading.Lock()
        rtrn_val = 1
        if mutex.acquire(1):
            conn = self.__connect()
            cu   = self.__cursor()
            try:
                if params == None:
                    rtrn_val = cu.executemany(sql)
                else:
                    rtrn_val = cu.executemany(sql, params)
            except MySQLdb.Error, e:
                print str(e)
                logger.error('[MYSQL]: insert many value failed:' + e.args[0])
                rtrn_val = 0
            finally:
                conn.commit()
                mutex.release()

    def do_update(self, sql, params):
        global logger
        logger.info('[MYSQL]: Update following sql:')
        logger.info(sql)
        import threading
        mutex = threading.Lock()
        rtrn_val = 1
        if mutex.acquire(1):
            conn = self.__connect()
            cu = self.__cursor()
            try:
                if params == None:
                    rtrn_val = cu.execute(sql)
                else:
                    rtrn_val = cu.execute(sql, params)
            except MySQLdb.Error, e:
                print str(e)
                logger.error('[MYSQL]: Update value failed:' + e.args[0])
                rtrn_val = 0
            finally:
                conn.commit()
                mutex.release()

        return rtrn_val

    def do_delete(self, sql, params):
        global logger
        logger.info('[MYSQL]: Delete following sql:')
        logger.info(sql)
        import threading
        mutex = threading.Lock()
        rtrn_val = 1
        if mutex.acquire(1):
           conn = self.__connect()
           cu = self.__cursor()
           try:
                if params == None:
                    rtrn_val = cu.execute(sql)
                else:
                    rtrn_val = cu.execute(sql, params)
           except MySQLdb.Error, e:
               print str(e)
               logger.error('[MYSQL]: Delete value failed:' + e.args[0])
               rtrn_val = 0
           finally:
               conn.commit()
               mutex.release()

        return rtrn_val

    def select_one(self, sql, params):
        conn = self.__connect()
        cu = self.__cursor()
        try:
            if params == None:
                cu.execute(sql)
            else:
                cu.execute(sql, params)
        except MySQLdb.Error, e:
            logger.info(('[MYSQL]: query one data failed: %s') % (e.args[0]))
            return None

        return cu.fetchone()

    def select_all(self, sql, params):
        conn = self.__connect()
        cu = self.__cursor()
        try:
            if params == None:
                cu.execute(sql)
            else:
                cu.execute(sql, params)
        except MySQLdb.Error, e:
            print str(e)
            logger.info(('[MYSQL]: query all data failed: %s') % (e.args[0]))
            return None

        return cu.fetchall()


if __name__ == "__main__":
    conn = MysqlDbConnection(
        'localhost',
        3306,
        'root',
        '111111',
        'qixindb'
    )
    conn.do_insert(
        '''
        INSERT INTO com_basic_info_t(com_oprt_range,com_website,com_reg_code,com_cert_date,com_credit_code,com_estb_date,com_oprt_time_range,com_state,com_tel,com_org_code,com_legal_prsnt,com_reg_org,com_type,com_name,com_reg_money,com_qixin_code,com_addr,com_shareholders,com_members) value (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        ''',
        [
            u'com_oprt_range:我的测试中文字符串',
            u'http://www.ahxkl.com.cn',
            u'340107000002651',
            u'2016-01-26',
            u'91340100704900058T',
            u'1995-05-19',
            u'1995-05-19 - -',
            u'公司状况',
            u'0551-65535618',
            u'704900058',
            u'法人代表',
            u'注册机构',
            u'注册单位但是问范玮琪分分发缺乏分期发发违法',
            '[{"shlder_name": "\\u5408\\u80a5\\u4e2d\\u822a\\u65b0\\u80fd\\u6e90\\u79d1\\u6280\\u6709\\u9650\\u8d23\\u4efb\\u516c\\u53f8", "shlder_real_paid": "--", "shlder_type": "\\u4f01\\u4e1a\\u6cd5\\u4eba", "shlder_paid": "2280 \\u4e07\\u4eba\\u6c11\\u5e012016\\u5e741\\u670821\\u65e5"}]',
            '[{"memb_name": "\\u8bb8\\u79c0\\u8363", "memb_job_title": "\\u8463\\u4e8b"}, {"memb_name": "\\u6bd5\\u6653\\u8273", "memb_job_title": "\\u76d1\\u4e8b"}, {"memb_name": "\\u8881\\u5b5d\\u53cb", "memb_job_title": "\\u8463\\u4e8b"}, {"memb_name": "\\u718a\\u826f\\u5e73", "memb_job_title": "\\u8463\\u4e8b"}, {"memb_name": "\\u6c5f\\u6000\\u8fdb", "memb_job_title": "\\u8463\\u4e8b"}, {"memb_name": "\\u848b\\u4f1f\\u660e", "memb_job_title": "\\u8463\\u4e8b\\u957f"}]'
        ]
    )
    conn.close()